package me.send.produce.client.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.send.business.base.tenpay.util.Constants;
import me.send.business.base.tenpay.util.MD5;
import me.send.business.base.tenpay.util.MD5Util;
import me.send.business.base.tenpay.util.TenpayUtil;
import me.send.business.base.tenpay.util.Util;
import me.send.business.service.bean.WxPayResult;
import me.send.business.service.pojo.BatchWithdrawRecord;
import me.send.business.service.pojo.WithdrawOrder;
import me.send.produce.client.controller.base.BaseController;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.InputSource;

@Controller
@RequestMapping(value = "/wallet")
public class WalletController extends BaseController {
	
	private final static Logger logger = LoggerFactory
			.getLogger(WalletController.class.getName());
	
	@RequestMapping(value="batch/order",produces = "text/html;charset=UTF-8")
	public ModelAndView queryBatchWithdrawOrder(Model model){
		ModelAndView modelAndView = new ModelAndView("/main/batch_withdraw_order.jsp");
		List<BatchWithdrawRecord> list=walletService.queryBatchWithdrawOrders();
		model.addAttribute("list",list);
		return modelAndView;
	}
	
	@RequestMapping(value="/request/alipay/batch",produces = "text/html;charset=UTF-8")
	public ModelAndView requestAliBatchPay(String batchOrderNo,HttpServletRequest request,HttpServletResponse response,Model model) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView("/main/alipay_batch.jsp");
		BatchWithdrawRecord record=walletService.queryBatchWithdrawOrderByOrderNo(batchOrderNo);
		List<WithdrawOrder> orders=walletService.queryWithdrawOrdersByBatchNo(batchOrderNo);
		StringBuffer detail_data=new StringBuffer();
		for(int i=0;i<orders.size();i++){
			WithdrawOrder order=orders.get(i);
			detail_data.append(order.getWithdrawOrderNo());
			detail_data.append("^");
			detail_data.append(order.getWithdrawAccountNo());
			detail_data.append("^");
			detail_data.append(order.getBrokerName());
			detail_data.append("^");
			detail_data.append(order.getWithdrawAmount().doubleValue());
			detail_data.append("^");
			detail_data.append(order.getWithdrawDesc()+"【经纪人提现】");
			if(i<orders.size()-1){
				detail_data.append("|");
			}
		}
		System.out.println(detail_data.toString());
		model.addAttribute("batch_no", batchOrderNo);
		model.addAttribute("batch_fee", record.getBatchFee().doubleValue()+"");
		model.addAttribute("batch_num", record.getBatchNum()+"");
		model.addAttribute("detail_data", detail_data.toString());
		return modelAndView;
		
	}


	/**
	 * 查询充值金额列表
	 * 
	 * @return
	 */
	@RequestMapping("/user/rechargeList")
	@ResponseBody
	public Map<String, Object> queryRechargeList() {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> list=walletService.queryRechargeList();
		result.put("code", 0);
		result.put("message", "success");
		result.put("datas", list);
		return result;
	}
	
	/**
	 * 查询付款详情列表
	 * 
	 * @return
	 */
	@RequestMapping("/user/payDetails")
	@ResponseBody
	public Map<String, Object> queryPayDetails(int orderid) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> order=orderService.queryOrder(orderid);
		result.put("code", 0);
		result.put("message", "success");
		result.put("datas", order);
		return result;
	}
	
	/**
	 * 查询优惠券列表
	 * @param userid
	 * @return
	 */
	@RequestMapping("/user/queryRedList")
	@ResponseBody
	public Map<String, Object> queryRedList(int userid){
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> list=walletService.queryRedAmountList(userid);
		result.put("code", 0);
		result.put("message", "success");
		result.put("datas", list);
		return result;
	}
	
	
	
	
	
	/**
	 * 微信支付生成prepayId
	 * 
	 * @param amount
	 * @param payType
	 * @param userId
	 * @return
	 */
	@RequestMapping("/user/buildPrepayId")
	@ResponseBody
	public Map<String, Object> buildPrepayId(HttpServletRequest request,HttpServletResponse response,String payOrderNo) {
		Map<String, Object> result = new HashMap<String, Object>();
		String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
		String entity = genProductArgs(payOrderNo,request);


		byte[] buf = Util.httpPost(url, entity);

		String content = new String(buf);
		logger.info(content);
		
		SAXBuilder builder = new SAXBuilder();
        StringReader read = new StringReader(content);
        InputSource source = new InputSource(read);
        Document document = null;
		try {
			document = builder.build(source);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.put("code", 1);
			result.put("message", "获取微信预支付订单号失败");
			e.printStackTrace();
			return result;
		}
        Element root = document.getRootElement();
        String prepay_id=root.getChildText("prepay_id");

        result.put("code", 0);
        result.put("message", "success");
		Map<String,String> prepayMap=new HashMap<String, String>();
		prepayMap.put("prepay_id", prepay_id);
		result.put("datas", prepayMap);
		return result;
	}
	
	
	/**
	 生成签名
	 */

	public static String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);
		

		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return packageSign;
	}
	
	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<"+params.get(i).getName()+">");


			sb.append(params.get(i).getValue());
			sb.append("</"+params.get(i).getName()+">");
		}
		sb.append("</xml>");

		return sb.toString();
	}
	
	private String genProductArgs(String out_trade_no,HttpServletRequest request) {
		StringBuffer xml = new StringBuffer();
        Map<String, Object> payOrderMap=walletService.getPayOrderByNo(out_trade_no);
        BigDecimal amount=(BigDecimal)payOrderMap.get("amount");
        Integer payWay=(Integer)payOrderMap.get("payWay");

		try {
			String	nonceStr = genNonceStr();


			xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
			if(payWay==0){//微信充值
				packageParams.add(new BasicNameValuePair("body", "呼送充值__"+out_trade_no));
			}else{//微信支付
				packageParams.add(new BasicNameValuePair("body", "呼送支付__"+out_trade_no));
			}
			packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url", "http://www.yihusong.com/produce.client/wallet/user/weixin/notify_url.htm"));
			packageParams.add(new BasicNameValuePair("out_trade_no",out_trade_no));
			packageParams.add(new BasicNameValuePair("spbill_create_ip","127.0.0.1"));
			packageParams.add(new BasicNameValuePair("total_fee", (int)(amount.doubleValue()*100)+""));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));


			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));


		   String xmlstring =toXml(packageParams);

			return xmlstring;

		} catch (Exception e) {
			return null;
		}
	}
	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}
	/**
	 * 为用户支付生成订单
	 * 
	 * @param amount
	 * @param payType
	 * @param userId
	 * @return
	 */
	@RequestMapping("/user/buildPayRecord")
	@ResponseBody
	public Map<String, Object> buildPayRecord(double amount, int payType,
			int userId, int orderid,int payWay,int redId) {
		Map<String, Object> result = new HashMap<String, Object>();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = sdf1.format(new Date());
//		String orderId = "HSRC" + sdf2.format(new Date()) + userId;
		
		//---------------生成订单号 开始------------------------  
        //当前时间 yyyyMMddHHmmss  
        String currTime = TenpayUtil.getCurrTime();  
        //8位日期  
        String strTime = currTime.substring(8, currTime.length());  
        //四位随机数  
        String strRandom = TenpayUtil.buildRandom(4) + "";  
        //10位序列号,可以自行调整。  
        String strReq = strTime + strRandom;  
        //订单号，此处用时间加随机数生成，商户根据自己情况调整，只要保持全局唯一就行  
        String orderId = strReq;  
      //---------------生成订单号 结束------------------------  
		
				
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("amount", amount);
		param.put("payType", payType);
		param.put("payWay", payWay);
		param.put("userId", userId);
		param.put("redId", redId);
		param.put("orderId", orderid);
		param.put("createTime", date);
		param.put("payOrderNo", orderId);
		walletService.buildPayRecord(param);
		result.put("code", 0);
		result.put("message", "success");
		result.put("datas", walletService.getPayOrderByNo(orderId));
		return result;
	}

	/**
	 * 用户确认订单信息后点击确认支付接口
	 * 
	 * @param payOrderNo
	 *            唯一订单号
	 * @return 订单详细信息
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/user/doPay")
	@ResponseBody
	public Map<String, Object> doPay(String payOrderNo,HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 0);
		result.put("message", "success");
		Map payOrderMap = walletService.getPayOrderByNo(payOrderNo);
		int payType=(Integer)payOrderMap.get("payType");
		if (payType==0) {
			// 支付宝回调地址 (域名后续加入配置中)
			payOrderMap.put("prepay_id", "");
			payOrderMap.put("notify_url",
					"http://www.yihusong.com/produce.client/wallet/user/alipay/notify_url.htm");
		} else if (payType==1) {
			// 微信回调地址（域名后续加入配置中）
			
			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs(payOrderNo,request);
			byte[] buf = Util.httpPost(url, entity);

			String content = new String(buf);
			logger.info(content);
			
			SAXBuilder builder = new SAXBuilder();
	        StringReader read = new StringReader(content);
	        InputSource source = new InputSource(read);
	        Document document = null;
			try {
				document = builder.build(source);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				result.put("code", 1);
				result.put("message", "获取微信预支付订单号失败");
				e.printStackTrace();
				return result;
			}
	        Element root = document.getRootElement();
	        
	        Map<String,String> prepay_map=new HashMap<String, String>();
	        String prepay_id=root.getChildText("prepay_id");
	        String appid=root.getChildText("appid");
	        String mch_id=root.getChildText("mch_id");
	        String nonce_str=root.getChildText("nonce_str");
//	        String sign=root.getChildText("sign");
	        String trade_type=root.getChildText("trade_type");
	        long timestame=genTimeStamp();
	        prepay_map.put("prepay_id", prepay_id);
	        prepay_map.put("appid", appid);
	        prepay_map.put("mch_id", mch_id);
	        prepay_map.put("nonce_str", nonce_str);
	        prepay_map.put("partnerid", Constants.API_KEY);
	        prepay_map.put("timestamp", timestame+"");
	        prepay_map.put("packages", "Sign=WXPay");
	        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
			signParams.add(new BasicNameValuePair("appid", appid));
			signParams.add(new BasicNameValuePair("noncestr", nonce_str));
			signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
			signParams.add(new BasicNameValuePair("partnerid", Constants.API_KEY));
			signParams.add(new BasicNameValuePair("prepayid", prepay_id));
			signParams.add(new BasicNameValuePair("timestamp", timestame+""));
	        prepay_map.put("sign", genAppSign(signParams));
	        prepay_map.put("trade_type", trade_type);
	        payOrderMap.put("prepay_map", prepay_map);
			payOrderMap.put("notify_url",
					"http://www.yihusong.com/produce.client/wallet/user/weixin/notify_url.htm");
		}
		result.put("datas", payOrderMap);
		return result;
	}
	
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

//        this.sb.append("sign str\n"+sb.toString()+"\n\n");
		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return appSign;
	}

	/**
	 * 查询用户钱包余额
	 * 
	 * @param userid
	 * @return
	 */
	@RequestMapping("/user/balance")
	@ResponseBody
	public Map<String, Object> balance(int userid) {
		Map<String, Object> result = new HashMap<String, Object>();
		double balance = walletService.userBalance(userid);
		result.put("code", 0);
		result.put("message", "success");
		result.put("balance", balance);
		return result;
	}

	/**
	 * 用户使用钱包余额进行支付
	 * 
	 * @param orderid
	 * @return
	 */
	@RequestMapping("/user/walletPay")
	@ResponseBody
	public Map<String, Object> walletPay(int orderid,int redid) {
		Map<String, Object> result = new HashMap<String, Object>();
		String s="fail";
		try {
			s = walletService.userWalletPay(orderid,redid);
		} catch (Exception e) {
		}
		if (s.equals("fail")) {
			result.put("code", 1);
			result.put("message", "支付失败,您的钱包余额不足，请充值后再进行支付");
		}else if("repeat".equals(s)){
			result.put("code", 2);
			result.put("message", "您的呼单已被支付过，不需要再支付了");
		} else {
			result.put("code", 0);
			result.put("message", "支付成功");
		}
		return result;
	}

	/**
	 * 支付宝支付回调接口
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("null")
	@RequestMapping(value="/user/alipay/notify_url", method = RequestMethod.POST)
	public void alipayNotify(HttpServletRequest request,HttpServletResponse response){
		logger.info("notify_alipay:begin");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			logger.info("notify_alipay:fail"+e1);
			e1.printStackTrace();
			out.println("fail");
		}
		String result="fail";
		try {
			result = walletService.notifyAlipayUser(request);
		} catch (Exception e) {
			logger.info("notify_alipay:fail"+e);
			e.printStackTrace();
			out.println("fail");
		}
		if("success".equals(result)){
			logger.info("notify_alipay:success");
			out.println("success");
		}else{
			logger.info("notify_alipay:fail");
			out.println("fail");
		}
	}

	/**
	 * 微信支付回调接口
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/user/weixin/notify_url", method = RequestMethod.POST)
	public void weixinNotify(HttpServletRequest request,
			HttpServletResponse response){
		logger.info("notify_weixin:begin");
		
		String inputLine;
		String notityXml = "";
		String resXml = "";
		try {
		while ((inputLine = request.getReader().readLine()) != null) {
		notityXml += inputLine;
		}
		request.getReader().close();
		logger.info("notify_weixin:begin [notityXml]"+notityXml.toString());

		Map m = parseXmlToList2(notityXml);
		logger.info("notify_weixin:back [map]"+m);
		Map<String,String> map=new TreeMap<String, String>();
		
		map.put("appid",m.get("appid").toString());
		map.put("mch_id", m.get("mch_id").toString());
		map.put("nonce_str", m.get("nonce_str").toString());
		map.put("sign", m.get("sign").toString());
		map.put("result_code", m.get("result_code").toString());
		map.put("openid", m.get("openid").toString());
		map.put("is_subscribe", m.get("is_subscribe").toString());
		map.put("trade_type",m.get("trade_type").toString());
		map.put("bank_type", m.get("bank_type").toString());
		map.put("total_fee", m.get("total_fee").toString());
		map.put("cash_fee", m.get("cash_fee").toString());
		map.put("transaction_id", m.get("transaction_id").toString());
		map.put("out_trade_no", m.get("out_trade_no").toString());
		map.put("time_end",m.get("time_end").toString());
		map.put("return_code", m.get("return_code").toString());
		if(m.get("device_info")!=null){
			map.put("device_info", m.get("device_info").toString());
		}
		if(m.get("err_code")!=null){
			map.put("err_code", m.get("err_code").toString());
		}
		if(m.get("err_code_des")!=null){
			map.put("err_code_des", m.get("err_code_des").toString());
		}
		if(m.get("fee_type")!=null){
			map.put("fee_type", m.get("fee_type").toString());
		}
		if(m.get("cash_fee_type")!=null){
			map.put("cash_fee_type", m.get("cash_fee_type").toString());
		}
		if(m.get("coupon_fee")!=null){
			map.put("coupon_fee", m.get("coupon_fee").toString());
		}
		if(m.get("coupon_count")!=null){
			map.put("coupon_count", m.get("coupon_count").toString());
		}
		if(m.get("attach")!=null){
			map.put("attach", m.get("attach").toString());
		}
		if(m.get("return_msg")!=null){
			map.put("return_msg", m.get("return_msg").toString());
		}
		
		logger.info("notify_weixin:md5 [map]"+map);
		
		StringBuilder sb = new StringBuilder();
		
		Set es = map.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			String v = (String)entry.getValue();
			if(null != v && !"".equals(v) 
					&& !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);
		String enc = TenpayUtil.getCharacterEncoding(request,response);
		String sign =MD5Util.MD5Encode(sb.toString(), enc).toUpperCase();
		String tenpaySign=m.get("sign").toString();
		if(tenpaySign.equals(sign)){
			WxPayResult wpr = new WxPayResult();
			wpr.setAppid(m.get("appid").toString());
			wpr.setBankType(m.get("bank_type").toString());
			wpr.setCashFee(m.get("cash_fee").toString());
			wpr.setIsSubscribe(m.get("is_subscribe").toString());
			wpr.setMchId(m.get("mch_id").toString());
			wpr.setNonceStr(m.get("nonce_str").toString());
			wpr.setOpenid(m.get("openid").toString());
			wpr.setOutTradeNo(m.get("out_trade_no").toString());
			wpr.setResultCode(m.get("result_code").toString());
			wpr.setReturnCode(m.get("return_code").toString());
			wpr.setSign(m.get("sign").toString());
			wpr.setTimeEnd(m.get("time_end").toString());
			wpr.setTotalFee(m.get("total_fee").toString());
			wpr.setTradeType(m.get("trade_type").toString());
			wpr.setTransactionId(m.get("transaction_id").toString());
			if(m.get("device_info")!=null){
				wpr.setDeviceInfo(m.get("device_info").toString());
			}
			if(m.get("fee_type")!=null){
				wpr.setFeeType(m.get("fee_type").toString());
			}
			
			logger.info("notify_weixin:begin [map]"+m);
			if("SUCCESS".equals(wpr.getResultCode())){
				try {
					walletService.notifyWeixinUser(wpr);
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				} catch (Exception e) {
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
					logger.info("notify_weixin:error [e]"+e);
					e.printStackTrace();
				}
				//支付成功
			}else{
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			}
			logger.info("notify_weixin:end [resXml]"+resXml.toString());
			BufferedOutputStream out = new BufferedOutputStream(
					response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		}else{
			logger.info("notify_weixin:fail verify sign="+sign+",tenpaySgin="+tenpaySign);
		}
		
		
		} catch (Exception e) {
			logger.info("notify_weixin:fail e="+e);
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map parseXmlToList2(String xml) {
		Map retMap = new HashMap();
		try {
		StringReader read = new StringReader(xml);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);
		// 创建一个新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();
		// 通过输入源构造一个Document
		org.jdom.Document doc =  sb.build(source);
		Element root = (Element) doc.getRootElement();// 指向根节点
		List<Element> es = root.getChildren();
		if (es != null && es.size() != 0) {
		for (Element element : es) {
		retMap.put(element.getName(), element.getValue());
		}
		}
		} catch (Exception e) {
		e.printStackTrace();
		}
		return retMap;
		}
	
		 @SuppressWarnings("unused")
		private static byte[] toByteArray(InputStream is) throws IOException {
		        ByteArrayOutputStream output = new ByteArrayOutputStream();
		        try {
		            byte[] b = new byte[16];
		            int n = 0;
		            while ((n = is.read(b)) != -1) {
		                output.write(b, 0, n);
		            }
		            return output.toByteArray();
		        } finally {
		            output.close();
		        }
		    }
		 
		 
		 @SuppressWarnings("rawtypes")
		public static void main(String[] args) throws Exception {
				
//			 sign=820FD7DB038A98877FCEEA2D9F53508A, 
	
	Map<String,String> m=new TreeMap<String, String>();
	m.put("device_info","APP-001");
	m.put("bank_type", "CMB_DEBIT");
	m.put("cash_fee", "1");
	m.put("fee_type", "CNY");
	m.put("is_subscribe", "N");
	m.put("mch_id", "1251474601");
	m.put("nonce_str", "1884486815");
	m.put("out_trade_no","1441776788");
	m.put("openid", "oBfZIwGR32M3pYBnMmMfvzwbWx1M");
	m.put("result_code", "SUCCESS");
	m.put("return_code", "SUCCESS");
	m.put("appid", "wx6131ca3318adce6d");
	m.put("time_end", "20150909133323");
	m.put("transaction_id","1008240824201509090827807035");
	m.put("trade_type", "APP");
	m.put("total_fee", "1");
	m.put("sign", "820FD7DB038A98877FCEEA2D9F53508A");
	
	
	Map<String,String> map=new TreeMap<String, String>();
	
	map.put("appid",m.get("appid").toString());
	map.put("mch_id", m.get("mch_id").toString());
	map.put("nonce_str", m.get("nonce_str").toString());
	map.put("sign", m.get("sign").toString());
	map.put("result_code", m.get("result_code").toString());
	map.put("openid", m.get("openid").toString());
	map.put("is_subscribe", m.get("is_subscribe").toString());
	map.put("trade_type",m.get("trade_type").toString());
	map.put("bank_type", m.get("bank_type").toString());
	map.put("total_fee", m.get("total_fee").toString());
	map.put("cash_fee", m.get("cash_fee").toString());
	map.put("transaction_id", m.get("transaction_id").toString());
	map.put("out_trade_no", m.get("out_trade_no").toString());
	map.put("time_end",m.get("time_end").toString());
	if(m.get("device_info")!=null){
		map.put("device_info", m.get("device_info").toString());
	}
	if(m.get("err_code")!=null){
		map.put("err_code", m.get("err_code").toString());
	}
	if(m.get("err_code_des")!=null){
		map.put("err_code_des", m.get("err_code_des").toString());
	}
	if(m.get("fee_type")!=null){
		map.put("fee_type", m.get("fee_type").toString());
	}
	if(m.get("cash_fee_type")!=null){
		map.put("cash_fee_type", m.get("cash_fee_type").toString());
	}
	if(m.get("coupon_fee")!=null){
		map.put("coupon_fee", m.get("coupon_fee").toString());
	}
	if(m.get("coupon_count")!=null){
		map.put("coupon_count", m.get("coupon_count").toString());
	}
	if(m.get("attach")!=null){
		map.put("attach", m.get("attach").toString());
	}
	if(m.get("return_code")!=null){
		map.put("return_code", m.get("return_code").toString());
	}
	if(m.get("return_msg")!=null){
		map.put("return_msg", m.get("return_msg").toString());
	}
	
	StringBuilder sb = new StringBuilder();
	
	Set es = map.entrySet();
	Iterator it = es.iterator();
	while(it.hasNext()) {
		Map.Entry entry = (Map.Entry)it.next();
		String k = (String)entry.getKey();
		String v = (String)entry.getValue();
		if(null != v && !"".equals(v) 
				&& !"sign".equals(k) && !"key".equals(k)) {
			sb.append(k + "=" + v + "&");
		}
	}
	sb.append("key=");
	sb.append(Constants.API_KEY);
	String sign =MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
//	String sign = genPackageSign(packageParams);
	System.out.println(sign);
	
//    String xmlDoc="<xml>"
//    		+ "<return_code><![CDATA[SUCCESS]]></return_code>"
//    		+ "<return_msg><![CDATA[OK]]></return_msg>"
//    		+ "<appid><![CDATA[wx6131ca3318adce6d]]></appid>"
//    		+ "<mch_id><![CDATA[1251474601]]></mch_id>"
//    		+ "<nonce_str><![CDATA[lZSdVJE0E149gshb]]></nonce_str>"
//    		+ "<sign><![CDATA[E6514682C3FD630ABDF6D46EC9A32CBB]]></sign>"
//    		+ "<result_code><![CDATA[SUCCESS]]></result_code>"
//    		+ "<prepay_id><![CDATA[wx20150910145500cd773c15760450113454]]></prepay_id>"
//    		+ "<trade_type><![CDATA[APP]]></trade_type>"
//    		+ "</xml>";
//    SAXBuilder builder = new SAXBuilder();
//    StringReader read = new StringReader(xmlDoc);
//    InputSource source = new InputSource(read);
//    Document document =builder.build(source);
//    Element root = document.getRootElement();
//    String prepay_id=root.getChildText("prepay_id");
//    System.out.println(prepay_id);
}

	   
}
